<template>
  <div class="user-info-container">
    <h2>用户信息</h2>
    <p v-if="loading">加载中...</p>
    <p v-else-if="errorMessage" style="color: red">{{ errorMessage }}</p>
    <p v-else>欢迎回来，{{ username }}</p>
    <button @click="handleLogout">退出登录</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api'

const username = ref('')
const router = useRouter()
const loading = ref(true)
const errorMessage = ref('')

const checkLoginStatus = () => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  if (!isLoggedIn) {
    router.push('/login')
  }
}

const fetchUserInfo = async () => {
  try {
    const token = localStorage.getItem('token')
    if (token) {
      api.defaults.headers.common['Authorization'] = `Bearer ${token}`
      const response = await api.get('/api/users/info')
      username.value = response.username
    }
  } catch (error) {
    errorMessage.value = error.response?.data?.message || '获取用户信息失败'
    console.error('获取用户信息错误:', error)
  } finally {
    loading.value = false
  }
}

const handleLogout = () => {
  localStorage.removeItem('isLoggedIn')
  localStorage.removeItem('token')
  delete api.defaults.headers.common['Authorization']
  router.push('/login')
}

onMounted(() => {
  checkLoginStatus()
  fetchUserInfo()
})
</script>

<style scoped>
.user-info-container {
  max-width: 300px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  text-align: center;
}

.user-info-container button {
  width: 100%;
  padding: 10px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
</style>